import pinyin from "../../utils/pinyin";

Page({
  data: {
    current: [],
    indexList: [],
    list: [],
  },

  handleGroupChange(event) {
    console.log("group", event);
    let selectedValue = event.detail.context.value;
    let current = this.data.current;
    // 查看当前选中的数值是否在数组中
    const index = current.indexOf(selectedValue);
    // 如果包含，则删除该值
    if (index > -1) {
      current.splice(index, 1);
    } else {
      // 如果不包含，则添加该值
      current.push(selectedValue);
    }
    this.setData({
      current,
    });
  },

  onLoad() {
  },

  onReady() {
    const originResult = [
      { label: "戴俊贤(13853500362)", value: "001" },
      { label: "袁涵容(18067541036)", value: "002" },
      { label: "林文林(19162638626)", value: "003" },
      { label: "吴明煦(17556504114)", value: "004" },
      { label: "冯嘉平(14585672448)", value: "005" },
      { label: "文绍钧(14550761328)", value: "006" },
      { label: "秦天泽(17348988737)", value: "007" },
      { label: "姜茂实(19857299448)", value: "008" },
      { label: "薛建本(16631058278)", value: "009" },
      { label: "尹飞龙(17699944302)", value: "010" },
      { label: "龙丝雨(18180365330)", value: "011" },
      { label: "许燕桦(18918072321)", value: "012" },
      { label: "朱凉夏(13275770240)", value: "013" },
      { label: "刘素华(13251187827)", value: "014" },
      { label: "蒋锦文(15085925154)", value: "015" },
      { label: "孔桂芝(18987831873)", value: "016" },
      { label: "阎思嫒(17713722031)", value: "017" },
      { label: "何景文(18815521029)", value: "018" },
      { label: "陈秀秀(18791873199)", value: "019" },
      { label: "金哲美(18323255342)", value: "020" },
    ];
    this.setData({
      list: this.transformData(originResult),
    });
    this.setData({
      indexList: this.data.list.map((item) => item.index),
    });
  },

  onSelect(e) {
    const { index } = e.detail;

    console.log(index);
  },

  getSurnameInitial(name) {
    // 假设名字格式是“姓(手机号)”
    const match = name.match(/(.+?)\(/);
    if (match) {
      const surname = match[1];
      return pinyin.getCamelFistChar(surname).toUpperCase();
    }
    return ""; // 如果没有匹配到或者转换失败，则返回空字符串
  },

  transformData(originResult) {
    const result = [];
    const initialMap = {};

    originResult.forEach((item) => {
      const surnameInitial = this.getSurnameInitial(item.label);
      if (!surnameInitial) return; // 跳过无法识别的姓氏

      if (!initialMap[surnameInitial]) {
        initialMap[surnameInitial] = [];
      }
      initialMap[surnameInitial].push(item);
    });

    for (let initial in initialMap) {
      result.push({
        index: initial,
        children: initialMap[initial].sort((a, b) =>
          a.label.localeCompare(b.label)
        ), // 对children按label排序
      });
    }

    result.sort((a, b) => a.index.localeCompare(b.index)); // 对结果按index排序
    return result;
  },
});
